/*
 * Copyright 2016 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kie.workbench.common.services.refactoring.backend.server.query.builder;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.util.automaton.RegExp;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm;

public abstract class AbstractQueryBuilder {

    public Query getQuery( ValueIndexTerm valueTerm ) {
            final String text = getText(valueTerm);
            Term term = new Term( valueTerm.getTerm(), text );

            Query termQuery;
            switch(valueTerm.getSearchType()) {
                case PREFIX:
                    termQuery = new PrefixQuery(term);
                    break;
                case WILDCARD:
                    termQuery = new WildcardQuery(term);
                    break;
                case REGEXP:
                    termQuery = new RegexpQuery(term, RegExp.NONE); // NONE until there's a specific reason to use extend regex syntax
                    break;
                case NORMAL:
                    termQuery = new TermQuery(term);
                    break;
                default:
                    throw new UnsupportedOperationException(ValueIndexTerm.TermSearchType.class.getSimpleName() + " value " + valueTerm.getSearchType().toString() + " is unsupported!");
            }

        return termQuery;
    }

    /**
     * The following are all special characters in lucene queries: </br>
     * <code>+ - && || ! ( ) { } [ ] ^ " ~ * ? : \</code>
     * </p>
     * However, only <code>-</code> is something that would be used in a name.
     *
     * @param term
     * @return
     */
    private String getText(ValueIndexTerm term) {
        return term.getValue().toLowerCase();
    }
}
